package com.vf.cloud.paas.app.master.api.tms.controller;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.vf.cloud.paas.app.master.api.tms.service.ITmsTile;
import com.vf.cloud.paas.app.master.common.repository.base.TmsTile;

@RestController
public class TmsController {

	@Autowired
	private ITmsTile tmsTileImpl;

	@GetMapping("/{layer}/{level}/{col}/{row}")
	public ResponseEntity<byte[]> xyz(@PathVariable String layer, @PathVariable String level, @PathVariable String col,
			@PathVariable String row, HttpServletResponse response) {
		String dataPath = "";
		StringBuffer buffer = new StringBuffer(dataPath);
		buffer.append(layer).append("\\").append(level).append("\\").append(col).append("\\").append(row);

		String key = buffer.toString();

		TmsTile tmsTile = tmsTileImpl.findById(key);

		String contentDisposition = ContentDisposition.builder("attachment").filename(row).build().toString();
		if (tmsTile != null) {
			return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
					.contentType(MediaType.APPLICATION_OCTET_STREAM).body(tmsTile.getContent().getData());
		} else {
			return ResponseEntity.badRequest()
					.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition + " Not Found")
					.contentType(MediaType.APPLICATION_OCTET_STREAM).body(null);
		}
	}

}
